﻿using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using IrisMembership.DataLayer;
using IrisMembership.DomainClasses;
using System.Data.Entity.Migrations;
using IrisMembership.Web.Authentication;
using System.Collections.Generic;
using System.ComponentModel;

namespace IrisMembership.Web.Migrations
{
    public class Configuration : DbMigrationsConfiguration<IrisDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(IrisDbContext context)
        {
            context.Roles.AddOrUpdate(x => x.Name, new Role { Name = "مدیر کل" }, new Role { Name = "کاربر" });





            var aa =
                Assembly.GetExecutingAssembly()
                    .GetTypes()
                    .Where(
                        x =>
                            x.BaseType == typeof(Controller) &&
                            x.CustomAttributes.Any(y => y.AttributeType == typeof(IrisAuthorize)))
                    .ToList();



            foreach (var controller in aa)
            {
                var controllerName = controller.Name.Replace("Controller", "").ToLower();

                var area =
                    controller.GetCustomAttributes(true).Where(x => x.GetType() == typeof(IrisAuthorize)).First() as IrisAuthorize;


                var areaName = area.AreaName;

                if (!string.IsNullOrEmpty(area.AreaName))
                {
                    areaName = area.AreaName.ToLower();
                }


                var permission = new Permission();

                permission.ControllerName = controllerName;

                permission.AreaName = areaName;


                var diplayNamAttr = (controller.GetCustomAttributes(true)
                        .Where(x => x.GetType() == typeof(DisplayNameAttribute))
                        .FirstOrDefault() as DisplayNameAttribute);

                if (diplayNamAttr != null)
                {
                    permission.PermissionName = diplayNamAttr.DisplayName;
                }
                else
                {
                    permission.PermissionName = areaName + "." + controllerName;
                }


                context.Permissions.AddOrUpdate(x => new { x.ControllerName, x.ActionName, x.AreaName }, permission);
                context.SaveChanges();

                List<Permission> methodPermissions = new List<Permission>();


                foreach (var methodInfo in controller.GetMethods().Where(x => x.GetCustomAttributes().All(y => y.GetType() != typeof(AllowAnonymousAttribute))).Where(x => (x.ReturnType == typeof(ActionResult) || x.ReturnType.BaseType == typeof(ActionResult))))
                {


                    var methodName = methodInfo.Name.ToLower();
                    var xzz = new Permission
                    {
                        ActionName = methodName,
                        ControllerName = controllerName,
                        AreaName = areaName,
                        ParentPermission = permission,
                    };

                    diplayNamAttr = (methodInfo.GetCustomAttributes(true)
                       .Where(x => x.GetType() == typeof(DisplayNameAttribute))
                       .FirstOrDefault() as DisplayNameAttribute);

                    if (diplayNamAttr != null)
                    {
                        xzz.PermissionName = diplayNamAttr.DisplayName;
                    }
                    else
                    {
                        xzz.PermissionName = areaName + "." + controllerName + "." + methodName;
                    }



                    methodPermissions.Add(xzz);

                }


                foreach (var methodPermission in methodPermissions.GroupBy(x => new { x.AreaName, x.ActionName, x.ControllerName }).Select(group => group.First()))
                {
                    context.Permissions.AddOrUpdate(x => new { x.ControllerName, x.ActionName, x.AreaName },
                                  methodPermission);
                }
            }




            //context.SaveChanges();



            context.SaveChanges();

            var role = context.Roles.First();

            foreach (var action in context.Permissions.ToList())
            {
                role.Permissions.Add(action);
            }







            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}
